/****************************************************
          File Name:copy.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Fri 06 Feb 2015 02:12:53 PM CST
*****************************************************/
/*
 * 复制文件空洞， 虽然效率很低, refer to ch-49/49-1.c
 */

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>

static void err(const char *s)
{
    perror(s);
    exit(errno);
}

int main(int argc, char *argv[])
{
    int fin, fout;
    int res = 0;
    struct stat tmp;

    if(argc != 3)
    {
        fprintf(stderr, "%s src dst\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    fin = open(argv[1],O_RDONLY);
    fout = open(argv[2], O_CREAT|O_RDWR, S_IRWXU);
    if(fin == -1 || fout == -1) err("open");

    fstat(fin, &tmp);

    lseek(fout, tmp.st_size, SEEK_END);
    lseek(fout, 0, SEEK_SET);

    while(read(fin, &res, 1))
    {
        if(res == '\0') lseek(fout, 1, SEEK_CUR);
        else
        write(fout, &res, 1);
    }

    errno = 0;
    close(fin);
    close(fout);
    if(errno) err("FATAL ERROR");
    else return 0;
}
